package com.onec.service.io.reactor;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class EchoServerReactor implements Runnable {

  Selector selector;

  ServerSocketChannel serverSocketChannel;

  public EchoServerReactor() throws ClosedChannelException {
    SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    selectionKey.attach(new AcceptorHandler());
  }

  @Override
  public void run() {
    while (!Thread.interrupted()) {
      try {
        selector.select();
        Set selected = selector.selectedKeys();
        Iterator iterator = selected.iterator();
        while (iterator.hasNext()) {
          SelectionKey selectionKey = (SelectionKey) iterator.next();
          dispatch(selectionKey);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }
  }

  // 反应器的分发操作
  private static void dispatch(SelectionKey selectionKey) {
    Runnable runnable = (Runnable) selectionKey.attachment();
    if (runnable != null) {
      runnable.run();
    }
  }

  // 处理器 处理新操作：
  class AcceptorHandler implements Runnable {

    @Override
    public void run() {
      try {
        SocketChannel channel = serverSocketChannel.accept();
        if (channel != null) {
          ;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
